package giermala.dominik.fotka.controller;

import giermala.dominik.fotka.domain.Foto;
import giermala.dominik.fotka.domain.User;
import giermala.dominik.fotka.repository.UserRepository;

import java.security.Principal;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoggedController {

	private static final Logger logger = LoggerFactory.getLogger(LoggedController.class);

	@Autowired
	private UserRepository userRepository;

	@RequestMapping(value = "/logged.html", method = RequestMethod.GET)
	public String logged(Locale locale, Model model, Principal principal, HttpServletRequest request) {
		logger.info("You are logged in");

		String username = principal.getName();
		User user = userRepository.findByUsername(username);

		request.getSession().setAttribute("user", user);
		
		List<Foto> fotos = user.getFotos();
		model.addAttribute("fotos", fotos);
		for(Foto foto: fotos) {
			logger.info("fotoName: "+foto.getName());
		}

		model.addAttribute("userId", user.getId());

		List<User> users = userRepository.findAll();
		StringBuilder sb = new StringBuilder();
		for (User u : users) {
			sb.append(String.valueOf(u));
		}
		String usersString = sb.toString();
		model.addAttribute("users", usersString);
		return "logged";
	}

}
